<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import type { Filters, ResourcePage } from '../models/Resource';
import { handelLoadResourcePage } from '../services/GetResourceService';
import ResourceDetail from '../components/ResourceDetail.vue';


const result = reactive<ResourcePage>({
    total: 0,
    pageIndex: 1,
    totalPages: 1,
    results: []
});

function prevPage() {
    if (result.pageIndex > 1) {
        result.pageIndex--;
        loadPage(result.pageIndex);
    }
}

function nextPage() {
    console.log('点击下一页:', result.pageIndex)
    if (result.pageIndex < result.totalPages) {
        result.pageIndex++;
        loadPage(result.pageIndex);
    }
}

const jumpPage = ref<number>(1);

function goToPage() {
    if (
        jumpPage.value >= 1 &&
        jumpPage.value <= result.totalPages &&
        jumpPage.value !== result.pageIndex
    ) {
        result.pageIndex = jumpPage.value;
        loadPage(result.pageIndex);
    }
}


const searchCache = ref<ResourcePage[]>([])
const normalCache = ref<ResourcePage[]>([])

const currentPageList = computed(() => {
    if (isSearch.value) {
        console.log('返回搜索缓存')
        return searchCache.value
    } else {
        console.log('返回正常缓存')
        return normalCache.value
    }
})
const query = ref('')
const isSearch = ref(false)

const filters = reactive<Filters>({
    category: 'null',
    time: 'null',
    sort: 'null'
})

let timer: number | null = null

watch([query, filters], ([newVal1, newVal2]) => {
    if (timer) clearTimeout(timer)
    timer = window.setTimeout(() => {
        console.log('关键词变化后触发加载', newVal1, newVal2)
        handleSearch()
    }, 800)
})

const handleSearch = () => {
    if (
        !query.value
        && filters.category === 'null'
        && filters.time === 'null'
        && filters.sort === 'null'
    ) {
        isSearch.value = false
        result.pageIndex = 1
        loadPage(result.pageIndex)
    } else {
        isSearch.value = true
        searchCache.value = []
        result.pageIndex = 1
        loadPage(result.pageIndex)
    }

}

// 模拟加载分页数据
function loadPage(pagepageIndex: number) {
    console.log(`加载第 ${pagepageIndex} 页的数据...此刻search:${isSearch.value}`)
    //到顶端
    window.scrollTo({ top: 0, behavior: 'instant' })
    // 如果缓存中有，直接使用
    if (currentPageList.value[pagepageIndex - 1]) {
        const cached = currentPageList.value[pagepageIndex - 1]
        result.total = cached.total
        result.pageIndex = cached.pageIndex
        result.totalPages = cached.totalPages
        result.results = cached.results
        console.log(`从缓存里加载第 ${pagepageIndex} 页的数据...`)
        return
    }
    // 模拟接口返回 ResourcePage
    handelLoadResourcePage(query.value, filters, pagepageIndex, isSearch.value)
        .then(simulated => {
            if (simulated) {
                // 存入缓存
                currentPageList.value[pagepageIndex - 1] = simulated
                console.log(`正常：${normalCache.value.length} 搜索：${searchCache.value.length} 当前：${currentPageList.value.length}...`)
                // 更新当前页结果
                result.total = simulated.total
                result.pageIndex = simulated.pageIndex
                result.totalPages = simulated.totalPages
                result.results = simulated.results
                console.log(`从接口里加载第 ${pagepageIndex} 页的数据...`)
            }
        })
}

let y = 0;
let detail = ref(false)
let rid = ref(0)
function goToDetail(id: number) {
    y = window.scrollY || document.documentElement.scrollTop
    
    localStorage.setItem('y', y.toString());
    localStorage.setItem('id', id.toString());
    localStorage.setItem('detail', 'true');
    localStorage.setItem('pageIndex', result.pageIndex.toString());
    console.log('查看资源细节id:', id);
    
    rid.value = id
    window.scrollTo(0, 0)
    detail.value = true
}
function handleGoBack(data: string) {
    localStorage.removeItem('y');
    localStorage.removeItem('id');
    localStorage.removeItem('detail');
    localStorage.removeItem('pageIndex');
    detail.value = false
     window.scrollTo({
        top: y,
        behavior: 'instant'
    })
    console.log(data)
}

onMounted(() => {
    const detail1 = localStorage.getItem('detail') === 'true';
    if (detail1) {
        console.log('重加载资源详情')
        detail.value = true
        rid.value = Number(localStorage.getItem('id'))
        y = Number(localStorage.getItem('y'))
        result.pageIndex = Number(localStorage.getItem('pageIndex'))
        loadPage(result.pageIndex)
    } else {
        loadPage(result.pageIndex)
    }
    
})
</script>
<template>
    <div v-if="detail">
        <ResourceDetail :resourceId=rid @goBack="handleGoBack" />
    </div>
    <div v-else>
        <div class="background">
            <div class="search-row">
                <div class="search-wrapper">
                    <input v-model="query" type="text" placeholder="请输入关键词" class="search-input" />
                </div>
            </div>
            <div class="filter-info">
                <div class="filters">
                    <!-- 分类筛选 -->
                    <div class="filter-group">
                        <label>分类筛选：</label>
                        <select v-model="filters.category">
                            <option value="null">全部</option>
                            <option value="document">文档</option>
                            <option value="video">视频</option>
                            <option value="voice">音频</option>
                            <option value="software">软件</option>
                            <option value="design">设计</option>
                            <option value="code">编程</option>
                            <option value="mod">工具</option>
                        </select>
                    </div>

                    <!-- 时间筛选 -->
                    <div class="filter-group">
                        <label>时间筛选：</label>
                        <select v-model="filters.time">
                            <option value="null">不限</option>
                            <option value="week">最近一周</option>
                            <option value="month">最近一个月</option>
                            <option value="year">最近一年</option>
                        </select>
                    </div>

                    <!-- 排序方式 -->
                    <div class="filter-group">
                        <label>排序方式：</label>
                        <select v-model="filters.sort">
                            <option value="null">综合排序</option>
                            <option value="latest">最新发布</option>
                            <option value="downloads">下载最多</option>
                            <option value="rating">评分最高</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <div class="result-grid">
            <!-- 循环展示模拟数据 -->
            <div v-for="(item, index) in result.results" :key="index" @click="goToDetail(item.id)"
                style="cursor: pointer">
                <div class="list-item">
                    <div class="left-column">
                        <h3>{{ item.title }}</h3>
                    </div>
                    <div class="right-column">
                        <p class="type">类型：{{ item.type }}</p>
                        <p class="rating">评分：{{ item.rating }}</p>
                        <p class="downloads">下载次数：{{ item.downloads }}</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="pagination">
            <p>
                <button @click="prevPage" :disabled="result.pageIndex === 1">上一页</button>
                <button @click="nextPage" :disabled="result.pageIndex === result.totalPages">下一页</button>
                跳转到
                <input type="number" v-model.number="jumpPage" min="1" :max="result.totalPages" style="width: 60px;" />
                <button @click="goToPage">跳转</button>
                当前第 {{ result.pageIndex }} 页 / 共 {{ result.totalPages }} 页
            </p>
        </div>
    </div>

</template>
<style scoped>
.container {
    padding: 16px;
}

.search-row {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 12px;
    margin-top: 60px;
}

.search-wrapper {
    display: flex;
    align-items: center;
    background: #ffffffcc;
    border-radius: 32px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    width: 500px;
}

.search-input {
    flex: 1;
    padding: 12px 20px;
    border: none;
    outline: none;
    font-size: 16px;
    border-radius: 32px 0 0 32px;
    background: transparent;
}

.filter-info {
    max-width: 100%;
    margin: 20px auto 40px;
    font-size: 14px;
    color: #333;
    user-select: none;
}

.filters {
    margin-top: 8px;
    display: flex;
    flex-wrap: wrap;
    gap: 20px 40px;
    justify-content: space-around;
}

.filter-group {
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 180px;
}

.filter-group label {
    font-weight: 600;
    color: #555;
    white-space: nowrap;
}

.filter-group select {
    padding: 4px 8px;
    border-radius: 6px;
    border: 1px solid #ccc;
    font-size: 14px;
    cursor: pointer;
    min-width: 100px;
}

.tag-cloud {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.tag-cloud button {
    background: #eee;
    border: none;
    border-radius: 14px;
    padding: 4px 12px;
    font-size: 13px;
    cursor: pointer;
    color: #666;
    transition: all 0.3s ease;
}

.tag-cloud button.active {
    background: #409eff;
    color: #fff;
    box-shadow: 0 2px 8px rgb(64 158 255 / 0.4);
}

.tag-cloud button:hover {
    background: #cce4ff;
    color: #409eff;
}

.result-grid {
    display: grid;
    grid-template-columns: repeat(1, 1fr);
    gap: 20px;
    max-width: 1200px;
    margin: 0 auto;
    padding: 30px 20px;
}

.result-card {
    background: rgba(255, 255, 255, 0.3);
    backdrop-filter: blur(10px);
    border-radius: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    transition: transform 0.3s ease;
    display: flex;
    flex-direction: column;
    height: 100%;
}

.result-card:hover {
    transform: translateY(-5px);
}

.result-image {
    width: 100%;
    aspect-ratio: 1/1;
    object-fit: cover;
    border-radius: 12px 12px 0 0;
}

.card-content {
    display: flex;
    flex-direction: column;
    flex: 1;
}

.card-text {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 20px;
    padding: 12px;
    text-align: left;
}

.list-item {
    display: flex;
    align-items: center;
    padding: 4px 0;
    border-bottom: 1px dashed #ccc;
}

.left-column {
    width: 120px;
    margin-left: 24px;
}

.left-column h3 {
    margin: 0;
    font-size: 16px;
}

.right-column {
    display: flex;
    flex-direction: row;
    gap: 12px;
    justify-content: flex-end;
    flex: 1;
    margin-left: -20px;
}

.right-column p {
    white-space: nowrap;
    width: auto;
    min-width: 50px;
}

.right-column .type {
    width: 100px;
}

.right-column .rating {
    width: 80px;
}

.right-column .downloads {
    width: 150px;
}

.pagination {
    text-align: center;
    margin-top: 40px;
    padding-bottom: 30px;
}

.pagination button,
.pagination input {
    margin: 0 6px;
}
</style>